import { formatTime } from "../../utils/time.js";

const storeName = "Person";
export default {
  init(dbInstance) {
    return {
      // 新增
      add(params = {}) {
        return new Promise((resolve, reject) => {
          try {
            // 打开指定的表
            let objectStore = dbInstance.getObejctStore(storeName);
            let createTime = formatTime(new Date());
            // 向 Person 表中写数据
            let request = objectStore.add({
              ...params,
              createTime,
            });
            request.onsuccess = (res) => {
              console.log(
                createTime,
                storeName + "表新增 ->> 数据库操作成功",
                request.result
              );
              resolve(res);
            };
            request.onerror = (err) => {
              console.log(
                createTime,
                storeName + "表新增 ->> 数据库操作失败",
                err
              );
              reject(err);
            };
          } catch (err) {
            reject(err);
          }
        });
      },
      // 删除
      delete(params) {
        return new Promise((resolve, reject) => {
          try {
            // 打开指定的表
            let objectStore = dbInstance.getObejctStore(storeName);
            let createTime = formatTime(new Date());
            // 删除指定id
            let request = objectStore.delete(params.id);
            request.onsuccess = (res) => {
              console.log(
                createTime,
                storeName + "表删除单条 ->> 数据库操作成功",
                request.result
              );
              resolve(request.result);
            };
            request.onerror = (err) => {
              console.log(
                createTime,
                storeName + "表删除单条 ->> 数据库操作失败",
                err
              );
              reject(err);
            };
          } catch (err) {
            reject(err);
          }
        });
      },
      // 通过id查询单条
      getOneById(params) {
        return new Promise((resolve, reject) => {
          try {
            // 打开指定的表
            let objectStore = dbInstance.getObejctStore(storeName);
            let createTime = formatTime(new Date());
            // get 方法接收一个主键id
            let request = objectStore.get(params);
            request.onsuccess = (res) => {
              console.log(
                createTime,
                storeName + "表根据id获取数据 ->> 数据库操作成功",
                request.result
              );
              resolve(request.result);
              // request.transaction.oncomplete = () => {
              //   resolve(request.result)
              // }
            };
            request.onerror = (err) => {
              console.log(
                createTime,
                storeName + "表根据id获取数据 ->> 数据库操作失败",
                err
              );
              reject(err);
            };
          } catch (err) {
            reject(err);
          }
        });
      },
      // 更新
      update(params) {
        return new Promise(async (resolve, reject) => {
          try {
            // 这里查询必须要放到新的事务上面，否则会报事务已经 finished
            let obj = await this.getOneById(params.id);
            // 等到查询完毕后，开启新事务
            let objectStore = dbInstance.getObejctStore(storeName);
            let createTime = formatTime(new Date());
            if (obj) {
              for (const key in params) {
                if (!!params[key]) {
                  obj[key] = params[key];
                }
              }
              // 更新数据
              let request = objectStore.put({
                ...obj,
                createTime,
              });
              request.onsuccess = (res) => {
                console.log(
                  createTime,
                  storeName + "表更新数据 ->> 数据库操作成功",
                  request.result
                );
                resolve(request.result);
              };
              request.onerror = (err) => {
                console.log(
                  createTime,
                  storeName + "表更新数据 ->> 数据库操作失败",
                  err
                );
                reject(err);
              };
            } else {
              resolve({ returnCode: -1, returnStr: "未查询到数据!" });
            }
          } catch (err) {
            reject(err);
          }
        });
      },
      // 查询全部
      selectAll() {
        return new Promise((resolve, reject) => {
          try {
            let objectStore = dbInstance.getObejctStore(storeName);
            let createTime = formatTime(new Date());
            // 遍历指定表中的所有数据
            let request = objectStore.openCursor();
            let list = [];
            // 这个方法会重复触发，直到数据循环完毕。
            request.onsuccess = (res) => {
              let cursor = res.target.result;
              if (cursor) {
                list.push(cursor.value);
                cursor.continue();
              } else {
                console.log(
                  createTime,
                  storeName + "表查询全部 ->> 数据库操作成功",
                  list
                );
                resolve(list);
              }
            };
            request.onerror = (err) => {
              console.log(
                createTime,
                storeName + "表查询全部 ->> 数据库操作失败",
                err
              );
              reject(err);
            };
          } catch (err) {
            reject(err);
          }
        });
      },
      // 清空一张表
      clearAll() {
        return new Promise((resolve, reject) => {
          try {
            let objectStore = dbInstance.getObejctStore(storeName);
            let createTime = formatTime(new Date());
            let request = objectStore.clear();
            request.onsuccess = (res) => {
              console.log(
                createTime,
                storeName + "表清空 ->> 数据库操作成功",
                request.result
              );
              resolve(request.result);
            };
            request.onerror = (err) => {
              console.log(
                createTime,
                storeName + "表清空 ->> 数据库操作失败",
                err
              );
              reject(err);
            };
          } catch (err) {
            reject(err);
          }
        });
      },
    };
  },
};
